package com.policyCloud.policyOauth.security;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义令牌属性
 */
public class CustomTokenEnhancer extends JwtAccessTokenConverter implements Serializable {
    private static int authenticateCodeExpiresTime = 10 * 60;

    private static final String TOKEN_SEG_USER_ID = "X-ZWY-UserId";
    private static final String TOKEN_SEG_CLIENT = "X-ZWY-ClientId";
    private static final String TOKEN_SEG_USERTYPE = "X-ZWY-UserType";
    private static final String TOKEN_SEG_USERNAME = "X-ZWY-UserName";

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                     OAuth2Authentication authentication) {
        CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
        userDetails.setClientId(authentication.getOAuth2Request().getClientId());
        authentication.setDetails(userDetails);
        Map<String, Object> info = new HashMap<>();
        info.put(TOKEN_SEG_USER_ID, userDetails.getUserId());

        DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);
        customAccessToken.setAdditionalInformation(info);

        OAuth2AccessToken enhancedToken = super.enhance(customAccessToken, authentication);
        enhancedToken.getAdditionalInformation().put(TOKEN_SEG_CLIENT, userDetails.getClientId());
        enhancedToken.getAdditionalInformation().put(TOKEN_SEG_USERTYPE, userDetails.getUserTypeId());
        enhancedToken.getAdditionalInformation().put(TOKEN_SEG_USERNAME, userDetails.getUsername());
        enhancedToken.getAdditionalInformation().put("authentication", userDetails.getAuthorities());
        return enhancedToken;
    }

}
